<template>
  <div class="appointment-list-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">我的预约</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/portal/patient' }">患者服务</el-breadcrumb-item>
          <el-breadcrumb-item>我的预约</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <!-- 主要内容 -->
    <div class="container main-content">
      <el-row :gutter="30">
        <!-- 左侧导航 -->
        <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="5">
          <div class="side-nav">
            <h3 class="side-nav-title">患者服务</h3>
            <el-menu
              class="side-menu"
              :default-active="activeMenu"
              @select="handleMenuSelect"
            >
              <el-menu-item index="appointment">
                <el-icon><Calendar /></el-icon>
                <span>预约挂号</span>
              </el-menu-item>
              <el-menu-item index="appointments">
                <el-icon><List /></el-icon>
                <span>我的预约</span>
              </el-menu-item>
              <el-menu-item index="records">
                <el-icon><Document /></el-icon>
                <span>就诊记录</span>
              </el-menu-item>
              <el-menu-item index="reports">
                <el-icon><DataAnalysis /></el-icon>
                <span>检查报告</span>
              </el-menu-item>
              <el-menu-item index="payment">
                <el-icon><Money /></el-icon>
                <span>费用查询</span>
              </el-menu-item>
              <el-menu-item index="prescription">
                <el-icon><List /></el-icon>
                <span>处方查询</span>
              </el-menu-item>
            </el-menu>
            
            <div class="service-card">
              <h3 class="service-card-title">
                <el-icon><Service /></el-icon> 服务热线
              </h3>
              <p class="service-phone">123-456-7890</p>
              <p class="service-time">周一至周日 8:00-18:00</p>
            </div>
          </div>
        </el-col>
        
        <!-- 右侧内容 -->
        <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="19">
          <div class="appointment-content">
            <!-- 搜索过滤 -->
            <div class="filter-section">
              <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="日期范围">
                  <el-date-picker
                    v-model="searchForm.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 350px;"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <!-- 预约列表 -->
            <div class="appointment-list">
              <div class="list-header">
                <div class="list-title">
                  <h2>预约列表</h2>
                  <span class="count-badge">共 {{ total }} 条</span>
                </div>
                <el-button type="primary" @click="navigateToAppointment">新增预约</el-button>
              </div>
              
              <el-table
                v-loading="loading"
                :data="appointmentList"
                style="width: 100%"
                empty-text="暂无预约记录"
                :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
              >
                <el-table-column type="index" label="序号" width="70" align="center" />
                <el-table-column prop="departmentName" label="科室" min-width="100" align="center" />
                <el-table-column prop="doctorName" label="医生" min-width="100" align="center" />
                <el-table-column label="预约日期" min-width="100" align="center">
                  <template #default="scope">
                    {{ formatAppointmentDate(scope.row.appointmentDate) }}
                  </template>
                </el-table-column>
                <el-table-column label="就诊时间" min-width="130" align="center">
                  <template #default="scope">
                    {{ formatTimeSlot(scope.row.timeSlot) }}
                  </template>
                </el-table-column>
                <el-table-column prop="visitType" label="就诊类型" min-width="100" align="center">
                  <template #default="scope">
                    {{ getVisitTypeLabel(scope.row.registrationType || scope.row.visitType) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" min-width="100" align="center">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="180" align="center">
                  <template #default="scope">
                    <el-button 
                      link 
                      type="primary" 
                      size="small"
                      @click="viewAppointment(scope.row)"
                    >
                      查看
                    </el-button>
                    <el-button 
                      v-if="scope.row.status === '预约中'"
                      link 
                      type="danger" 
                      size="small"
                      @click="cancelAppointment(scope.row)"
                    >
                      取消
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[10, 20, 30, 50]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                ></el-pagination>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="预约详情"
      width="1000px"
      top="5vh"
    >
      <div class="appointment-detail" v-if="currentAppointment">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-section">
              <h3 class="detail-section-title">基本信息</h3>
              <div class="detail-item">
                <span class="detail-label">预约号：</span>
                <span class="detail-value">{{ currentAppointment.appointmentId || currentAppointment.appointmentNumber }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">创建时间：</span>
                <span class="detail-value">{{ formatDate(currentAppointment.createdAt) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">状态：</span>
                <span class="detail-value">
                  <el-tag :type="getStatusType(currentAppointment.status)">
                    {{ getStatusLabel(currentAppointment.status) }}
                  </el-tag>
                </span>
              </div>
              <div class="detail-item" v-if="currentAppointment.paymentStatus">
                <span class="detail-label">支付状态：</span>
                <span class="detail-value">{{ currentAppointment.paymentStatus }}</span>
              </div>
              <div class="detail-item" v-if="currentAppointment.registrationFee">
                <span class="detail-label">挂号费：</span>
                <span class="detail-value">¥{{ currentAppointment.registrationFee }}</span>
              </div>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="detail-section">
              <h3 class="detail-section-title">就诊信息</h3>
              <div class="detail-item">
                <span class="detail-label">就诊科室：</span>
                <span class="detail-value">{{ currentAppointment.departmentName }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">就诊医生：</span>
                <span class="detail-value">{{ currentAppointment.doctorName }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">预约日期：</span>
                <span class="detail-value">{{ formatAppointmentDate(currentAppointment.appointmentDate) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">就诊时间：</span>
                <span class="detail-value">{{ formatTimeSlot(currentAppointment.timeSlot) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">时间段：</span>
                <span class="detail-value">{{ currentAppointment.period }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">就诊类型：</span>
                <span class="detail-value">{{ getVisitTypeLabel(currentAppointment.registrationType || currentAppointment.visitType) }}</span>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <div class="detail-section">
              <h3 class="detail-section-title">其他信息</h3>
              <div class="detail-item" v-if="currentAppointment.symptoms">
                <span class="detail-label">症状描述：</span>
                <span class="detail-value">{{ currentAppointment.symptoms }}</span>
              </div>
              <div class="detail-item" v-if="currentAppointment.remarks">
                <span class="detail-label">备注：</span>
                <span class="detail-value">{{ currentAppointment.remarks }}</span>
              </div>
              <div class="detail-item" v-if="!currentAppointment.symptoms && !currentAppointment.remarks">
                <span class="detail-value">暂无其他信息</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="currentAppointment && currentAppointment.status === '预约中'"
            type="danger" 
            @click="cancelAppointmentInDialog"
          >
            取消预约
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 取消原因对话框 -->
    <el-dialog
      v-model="cancelReasonDialogVisible"
      title="取消预约"
      width="500px"
    >
      <div class="cancel-reason-form">
        <p class="cancel-notice">请输入取消预约的原因：</p>
        <el-form :model="cancelReasonForm">
          <el-form-item>
            <el-input
              v-model="cancelReasonForm.reason"
              type="textarea"
              :rows="4"
              placeholder="请输入取消原因，例如：时间冲突、病情好转等"
            ></el-input>
          </el-form-item>
        </el-form>
        <p class="cancel-warning">注意：根据医院规定，距离预约时间不足24小时的预约无法取消。</p>
        <p class="cancel-info">取消预约后，该时段将释放给其他患者。如有问题请联系客服。</p>
        <p class="cancel-info">请确保您是此预约的患者本人，否则可能无法取消。</p>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelReasonDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancelAppointment">确认取消预约</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar, List, Document, DataAnalysis, Money, Service } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { appointmentAPI } from '@/utils/api'

const router = useRouter()
const userStore = useUserStore()
const activeMenu = ref('appointments')
const loading = ref(false)
const appointmentList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const detailDialogVisible = ref(false)
const currentAppointment = ref(null)
const cancelReasonDialogVisible = ref(false)
const cancelReasonForm = reactive({
  reason: '',
  appointment: null
})

// 搜索表单
const searchForm = reactive({
  dateRange: []
})

// 处理菜单选择
const handleMenuSelect = (key) => {
  router.push(`/portal/patient/${key}`)
}

// 获取预约列表
const fetchAppointments = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  loading.value = true
  
  try {
    // 获取患者ID
    const patientId = getPatientId()
    
    if (!patientId) {
      ElMessage.warning('无法获取患者信息，请重新登录')
      return
    }
    
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      patientId: patientId
    }
    
    // 添加日期范围过滤
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    console.log('查询参数:', params)
    
    // 确保token存在
    if (!localStorage.getItem('token') && userStore.token) {
      localStorage.setItem('token', userStore.token)
    }
    
    const res = await appointmentAPI.getAppointments(params)
    
    if (res.success && res.data) {
      // 处理返回的预约数据
      appointmentList.value = res.data.appointments || res.data.items || []
      total.value = res.data.total || appointmentList.value.length
      
      // 如果没有预约记录
      if (appointmentList.value.length === 0) {
        ElMessage.info('暂无预约记录')
      }
    } else {
      // 如果API请求成功但没有数据，使用本地存储中的最新预约数据
      useLocalAppointmentData()
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败，请稍后再试')
    // 使用本地存储中的最新预约数据
    useLocalAppointmentData()
  } finally {
    loading.value = false
  }
}

// 使用本地存储的预约数据
const useLocalAppointmentData = () => {
  // 尝试从本地存储获取上次成功的预约数据
  const lastAppointmentStr = localStorage.getItem('lastAppointment')
  if (lastAppointmentStr) {
    try {
      const lastAppointment = JSON.parse(lastAppointmentStr)
      
      // 转换为预约列表项格式
      const appointment = {
        id: `local-${Date.now()}`,
        appointmentId: lastAppointment.appointmentNumber || `AP${Date.now().toString().substr(-8)}`,
        appointmentNumber: lastAppointment.appointmentNumber || `AP${Date.now().toString().substr(-8)}`,
        departmentName: lastAppointment.departmentName,
        doctorName: lastAppointment.doctorName,
        appointmentDate: lastAppointment.appointmentDate,
        timeSlot: lastAppointment.appointmentTime || lastAppointment.timeSlot || "08:00:00-11:30:00",
        period: lastAppointment.period || "上午",
        patientName: lastAppointment.patientName || userStore.name || '当前用户',
        patientGender: lastAppointment.patientGender || '未知',
        patientPhone: lastAppointment.patientPhone || '未设置',
        status: lastAppointment.status || 'pending',
        paymentStatus: lastAppointment.paymentStatus || '未支付',
        createdAt: lastAppointment.date || new Date().toISOString(),
        registrationType: lastAppointment.registrationType || lastAppointment.visitType || 'specialist',
        visitType: lastAppointment.visitType || '初诊',
        symptoms: lastAppointment.symptoms || '',
        remarks: lastAppointment.remarks || ''
      }
      
      // 添加到列表的最前面
      appointmentList.value = [appointment, ...appointmentList.value]
      total.value = appointmentList.value.length
      
      console.log('已从本地存储加载预约数据:', appointment)
    } catch (error) {
      console.error('解析本地预约数据失败:', error)
    }
  }
}

// 查看预约详情
const viewAppointment = (appointment) => {
  currentAppointment.value = appointment
  
  // 如果缺少患者信息，尝试获取当前登录用户的信息
  if (!appointment.patientName || !appointment.patientGender || !appointment.patientPhone) {
    enrichPatientInfo(appointment)
  }
  
  detailDialogVisible.value = true
}

// 补充患者信息
const enrichPatientInfo = (appointment) => {
  // 优先使用预约中已有的患者信息
  appointment.patientName = appointment.patientName || '未知'
  appointment.patientGender = appointment.patientGender || '未知'
  appointment.patientPhone = appointment.patientPhone || '未知'
  
  // 如果缺少信息，尝试从用户存储中获取
  if (appointment.patientName === '未知' || appointment.patientGender === '未知' || appointment.patientPhone === '未知') {
    if (userStore.userInfo) {
      // 姓名
      if (appointment.patientName === '未知') {
        appointment.patientName = userStore.userInfo.name || userStore.name || '未知'
      }
      
      // 性别
      if (appointment.patientGender === '未知') {
        if (userStore.userInfo.gender === '男' || userStore.userInfo.gender === 'male') {
          appointment.patientGender = '男'
        } else if (userStore.userInfo.gender === '女' || userStore.userInfo.gender === 'female') {
          appointment.patientGender = '女'
        } else {
          appointment.patientGender = '未知'
        }
      }
      
      // 手机号
      if (appointment.patientPhone === '未知') {
        appointment.patientPhone = userStore.userInfo.phone || userStore.userInfo.phoneNumber || '未知'
      }
    }
  }
  
  console.log('补充后的患者信息:', appointment)
}

// 获取用户身份验证状态
const checkUserAndPatient = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  
  if (!userStore.userInfo) {
    ElMessage.warning('无法获取用户信息，请重新登录')
    return false
  }
  
  return true
}

// 根据预约显示提示信息
const displayAppointmentInfo = (appointment) => {
  let message = `预约科室：${appointment.departmentName || '未知科室'}\n`
  message += `预约医生：${appointment.doctorName || '未知医生'}\n`
  message += `预约日期：${formatAppointmentDate(appointment.appointmentDate)}\n`
  message += `预约时段：${formatTimeSlot(appointment.timeSlot)}\n`
  
  ElMessageBox.alert(message, '即将取消的预约', {
    confirmButtonText: '继续取消',
    type: 'warning',
    dangerouslyUseHTMLString: true
  }).then(() => {
    cancelReasonForm.appointment = appointment
    cancelReasonForm.reason = ''
    cancelReasonDialogVisible.value = true
  }).catch(() => {
    // 用户取消操作
  })
}

// 取消预约
const cancelAppointment = (appointment) => {
  // 先检查用户是否登录
  if (!checkUserAndPatient()) return
  
  // 检查当前状态是否允许取消
  if (appointment.status !== '预约中') {
    ElMessage.warning('只有"预约中"状态的预约可以取消')
    return
  }
  
  // 显示预约信息，让用户确认要取消的是哪个预约
  displayAppointmentInfo(appointment)
}

// 在对话框中取消预约
const cancelAppointmentInDialog = () => {
  if (!currentAppointment.value) return
  
  // 先检查用户是否登录
  if (!checkUserAndPatient()) return
  
  // 检查当前状态是否允许取消
  if (currentAppointment.value.status !== '预约中') {
    ElMessage.warning('只有"预约中"状态的预约可以取消')
    return
  }
  
  cancelReasonForm.appointment = currentAppointment.value
  cancelReasonForm.reason = ''
  cancelReasonDialogVisible.value = true
  detailDialogVisible.value = false
}

// 获取患者ID
const getPatientId = () => {
  if (!userStore.userInfo) return null
  
  // 尝试多种方式获取患者ID
  if (userStore.userInfo.patientId) {
    return userStore.userInfo.patientId
  } else if (userStore.userInfo.patient && userStore.userInfo.patient.id) {
    return userStore.userInfo.patient.id
  } else if (userStore.userInfo._id) {
    return userStore.userInfo._id
  } else if (userStore.userInfo.id) {
    return userStore.userInfo.id
  }
  
  return null
}

// 获取取消预约的详细错误信息
const getErrorMessage = (error) => {
  let errorMessage = '取消预约失败，请稍后再试'
  
  // 检查错误对象格式
  if (!error) return errorMessage
  
  // 直接使用错误对象的message属性
  if (error.message) {
    errorMessage = error.message
  }
  
  // 检查response.data
  if (error.response && error.response.data) {
    const responseData = error.response.data
    
    // 检查标准API错误格式
    if (responseData.message) {
      errorMessage = responseData.message
    }
    
    // 处理特定错误类型
    if (responseData.error === 'user_permissions') {
      return '您没有权限取消此预约。请确保您是预约的患者本人，如需帮助请联系医院客服。'
    }
  }
  
  // 检查错误数据结构
  if (typeof error === 'object' && error.data) {
    // 检查特定错误类型
    if (error.data.error === 'user_permissions') {
      return '您没有权限取消此预约。请确保您是预约的患者本人，如需帮助请联系医院客服。'
    }
    
    // 使用API提供的错误消息
    if (error.data.message) {
      return error.data.message
    }
  }
  
  // 处理常见错误情况
  if (errorMessage.includes('24小时') || errorMessage.includes('不足24小时')) {
    return '预约时间不足24小时，无法取消。如有特殊情况，请联系医院客服。'
  }
  
  if (errorMessage.includes('不存在')) {
    return '预约记录不存在或已被处理'
  }
  
  if (errorMessage.includes('已取消')) {
    return '该预约已经被取消'
  }
  
  if (errorMessage.includes('权限') || errorMessage.includes('permission')) {
    return '您没有权限取消此预约。请确保您是预约的患者本人，如需帮助请联系医院客服。'
  }
  
  return errorMessage
}

// 确认取消预约前添加额外验证
const confirmCancelAppointment = () => {
  if (!cancelReasonForm.appointment) return
  
  // 再次验证用户身份
  if (!checkUserAndPatient()) return
  
  // 添加患者ID信息到请求中
  const patientId = getPatientId()
  if (!patientId) {
    ElMessage.warning('无法确认您的患者身份，请重新登录或联系客服')
    return
  }
  
  ElMessageBox.confirm(
    '确定要取消该预约吗？取消后将无法恢复',
    '取消预约',
    {
      confirmButtonText: '确定取消',
      cancelButtonText: '再想想',
      type: 'warning'
    }
  ).then(() => {
    doCancelAppointment(cancelReasonForm.appointment, cancelReasonForm.reason)
    cancelReasonDialogVisible.value = false
  }).catch(() => {
    // 用户取消操作
  })
}

// 执行取消预约时包含患者ID
const doCancelAppointment = async (appointment, cancelReason) => {
  // 再次检查用户是否登录
  if (!checkUserAndPatient()) return
  
  loading.value = true
  
  try {
    // 处理本地模拟数据（id以local-开头）
    if (appointment.id && appointment.id.toString().startsWith('local-')) {
      // 直接在本地更新状态
      const index = appointmentList.value.findIndex(item => item.id === appointment.id)
      if (index !== -1) {
        appointmentList.value[index].status = 'cancelled'
        appointmentList.value[index].remarks = cancelReason || '患者主动取消'
        ElMessage.success('预约已取消')
      }
      return
    }
    
    // 简化请求参数，只传递必要的信息
    const params = {
      remarks: cancelReason || '患者主动取消'
    }
    
    // 输出请求信息，帮助调试
    console.log('取消预约，ID:', appointment.id, '参数:', params)
    
    // 确保token存在
    if (!localStorage.getItem('token') && userStore.token) {
      localStorage.setItem('token', userStore.token)
    }
    
    // 直接调用API，简化请求过程
    const res = await appointmentAPI.cancelAppointment(appointment.id, params)
    
    if (res.success) {
      ElMessage.success('预约已取消')
      // 刷新预约列表
      fetchAppointments()
    } else {
      throw res
    }
  } catch (error) {
    console.error('取消预约失败:', error)
    
    // 打印更多错误信息以便调试
    if (error.response) {
      console.error('错误响应:', error.response.data || error.response)
    }
    
    // 获取详细的错误信息
    const errorMessage = getErrorMessage(error)
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAppointments()
}

// 重置搜索
const resetSearch = () => {
  searchForm.dateRange = []
  currentPage.value = 1
  fetchAppointments()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchAppointments()
}

// 处理每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchAppointments()
}

// 导航到预约页面
const navigateToAppointment = () => {
  router.push('/portal/patient/appointment')
}

// 格式化预约时间
const formatAppointmentTime = (date, time) => {
  if (!date) return ''
  return `${date} ${time || ''}`
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'completed': '已完成',
    'cancelled': '已取消',
    'no_show': '未到诊',
    '预约中': '待确认',
    '已到诊': '已完成',
    '已取消': '已取消',
    '未到诊': '未到诊'
  }
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'confirmed': 'success',
    'completed': 'success',
    'cancelled': 'info',
    'no_show': 'danger',
    '预约中': 'warning',
    '已到诊': 'success',
    '已取消': 'info',
    '未到诊': 'danger'
  }
  return typeMap[status] || ''
}

// 获取就诊类型标签
const getVisitTypeLabel = (type) => {
  const types = {
    'expert': '专家门诊',
    'specialist': '专科门诊',
    'general': '普通门诊'
  }
  return types[type] || type
}

// 格式化预约日期（只显示日期部分）
const formatAppointmentDate = (dateStr) => {
  if (!dateStr) return ''
  // 如果包含T，表示是ISO格式的日期，需要提取前面的部分
  if (dateStr.includes('T')) {
    return dateStr.split('T')[0]
  }
  return dateStr
}

// 格式化时间段
const formatTimeSlot = (timeSlot) => {
  if (!timeSlot) return ''
  return timeSlot
}

// 检查是否可以取消预约
const canCancelAppointment = (status) => {
  // 严格按照后端要求，只有"预约中"状态的预约可以取消
  return status === '预约中'
}

// 页面加载时获取预约列表
onMounted(() => {
  fetchAppointments()
})
</script>

<style scoped>
.appointment-list-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1300px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  margin-bottom: 40px;
}

.side-nav {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.side-nav-title {
  font-size: 18px;
  margin: 0;
  padding: 20px;
  background: #1989fa;
  color: white;
}

.side-menu {
  border-right: none;
}

.service-card {
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-top: 1px solid #ebeef5;
}

.service-card-title {
  font-size: 16px;
  color: #1989fa;
  margin: 0 0 15px;
  display: flex;
  align-items: center;
}

.service-card-title .el-icon {
  margin-right: 8px;
}

.service-phone {
  font-size: 18px;
  font-weight: bold;
  color: #1989fa;
  margin: 0 0 5px;
}

.service-time {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.appointment-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  width: 100%;
}

.filter-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-title {
  display: flex;
  align-items: center;
}

.list-title h2 {
  font-size: 18px;
  margin: 0;
}

.count-badge {
  font-size: 14px;
  color: #909399;
  margin-left: 10px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.appointment-detail {
  padding: 0 10px;
}

.detail-section {
  margin-bottom: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
  height: calc(100% - 30px);
  min-height: 180px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  border: 1px solid #eee;
}

.detail-section-title {
  font-size: 16px;
  margin: 0 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
  font-weight: bold;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  line-height: 1.5;
}

.detail-label {
  width: 80px;
  color: #606266;
  font-weight: bold;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-word;
}

.el-row {
  margin-bottom: 0 !important;
}

.el-col {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .appointment-content {
    padding: 20px;
  }
  
  .side-nav {
    margin-bottom: 20px;
  }
  
  .filter-section .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}

.cancel-notice {
  margin-bottom: 15px;
  font-size: 14px;
  color: #303133;
}

.cancel-warning {
  margin-top: 15px;
  font-size: 12px;
  color: #E6A23C;
}

.cancel-info {
  margin-top: 10px;
  font-size: 12px;
  color: #409EFF;
}

.cancel-reason-form {
  padding: 0 15px;
}
</style> 